import localforage from 'localforage';

class AimeLocalforage {
  private aimeLocalforage!: LocalForage;
  private groupId: string;
  constructor(private appId: string, private userId: string) {
    this.aimeLocalforage = localforage.createInstance({
      name: `aime_${appId}_${userId}`
    });
    this.groupId = '';
  }
  // 设置对话组
  pushGroupId(groupId: string) {
    this.getGroupIds().then((groupIdArr = []) => {
      this.aimeLocalforage.setItem('groupIds', [...(groupIdArr as string[]), groupId]);
    });
  }
  // 获取上一个对话组id
  getLastGroupId() {
    return this.getGroupIds().then((groupIdArr = []) => {
      if (this.groupId) {
        const index = groupIdArr.findIndex(groupId => groupId === this.groupId);
        if (index !== -1) {
          this.groupId = groupIdArr[index - 1] || '';
        } else {
          this.groupId = '';
        }
      } else {
        this.groupId = groupIdArr[groupIdArr.length - 1] || '';
      }
      return this.groupId;
    });
  }
  // 获取对话组id数组
  getGroupIds(): Promise<string[]> {
    // @ts-ignore
    return this.aimeLocalforage.getItem('groupIds').then(groupIdArr => groupIdArr || []);
  }
}

export default AimeLocalforage;
